// position_list_item.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../data/models/buy_record_model.dart';

import '../../../data/models/sell_record_model.dart';
import '../controllers/position_controller.dart';
import 'trade_history_page.dart';

class StockPositionListItem extends StatefulWidget {
  final ObservableStockPosition observablePosition;
  final double filterPercent;
  final int refreshTrigger;
  final Function(String, GlobalKey) registerItemKey;
  final Function(String) unregisterItemKey;

  const StockPositionListItem({
    super.key,
    required this.observablePosition,
    required this.filterPercent,
    required this.refreshTrigger,
    required this.registerItemKey,
    required this.unregisterItemKey,
  });

  @override
  StockPositionListItemState createState() => StockPositionListItemState();
}

class StockPositionListItemState extends State<StockPositionListItem> {
  final PositionController _controller = Get.find();
  int _lastRefreshTrigger = 0;

  // 添加可见项跟踪相关变量
  final Map<String, GlobalKey> _itemKeys = <String, GlobalKey>{};
  final GlobalKey _itemKey = GlobalKey();



  @override
  void initState() {
    super.initState();
    _lastRefreshTrigger = widget.refreshTrigger;
    widget.registerItemKey(widget.observablePosition.position.symbol, _itemKey);


    // 注册列表项的GlobalKey到控制器
    /*if (!_controller.isControllerClosed) {
      _controller.registerItemKey(widget.observablePosition.position.symbol, _itemKey);
    }*/

  }

  @override
  void dispose() {
    widget.unregisterItemKey(widget.observablePosition.position.symbol);

    // 取消注册列表项的GlobalKey
   /* if (!_controller.isControllerClosed) {
      _controller.unregisterItemKey(widget.observablePosition.position.symbol);
    }*/
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant StockPositionListItem oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.refreshTrigger != _lastRefreshTrigger) {
      _lastRefreshTrigger = widget.refreshTrigger;
    }
  }

  void _showTradeHistory() {
    showDialog(
      context: context,
      builder:
          (context) =>
          TradeHistoryPage(position: widget.observablePosition.position),
    );
  }

  void _addBuyRecord() {
    Get.toNamed(
      '/addBuyRecord',
      arguments: {
        'symbol': widget.observablePosition.position.symbol,
        'name': widget.observablePosition.position.name,
      },
    )?.then((result) {
      // 当卖出页面返回时，如果结果为true则刷新数据
      if (result == true) {
        _controller.refreshData();
      }
    });
  }

  void _sellStock() async{
    if (widget.observablePosition.position.totalQuantity > 0) {
        Get.toNamed(
        '/sellStock',
        arguments: {
          'symbol': widget.observablePosition.position.symbol,
          'name': widget.observablePosition.position.name,
          'availableQuantity': widget.observablePosition.position.totalQuantity,
          'buyRecordsId': widget.observablePosition.position.buyRecords.first.id,
        },
      )?.then((result) {
        // 当卖出页面返回时，如果结果为true则刷新数据
        if (result == true) {
          _controller.refreshData();
        }
      });
    } else {
      Get.snackbar('提示', '该股票暂无持仓，无法卖出', snackPosition: SnackPosition.BOTTOM);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      // 移除 key: _controller.listViewKey,
      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
      child: Column(
        children: [
          // 股票基本信息行
          ListTile(
            title: Text(
              '${widget.observablePosition.position.name} (${widget.observablePosition.position.symbol})',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 4),
                Text(
                  '持仓: ${widget.observablePosition.position.totalQuantity}股',
                ),
                Text(
                  '成本: ${widget.observablePosition.position.averageCost.toStringAsFixed(2)}',
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    const Text('浮动盈亏: '),
                    // 使用GetBuilder替代Obx
                    GetBuilder<PositionController>(
                      builder: (controller) {
                        final position = widget.observablePosition.position;
                        final currentPrice =
                            widget.observablePosition.currentPrice.value;


                        final floatingProfitLoss =
                            (currentPrice - position.averageCost) *
                                position.totalQuantity;
                        final floatingProfitLossPercent =
                        position.averageCost > 0
                            ? ((currentPrice - position.averageCost) /
                            position.averageCost) *
                            100
                            : 0.0;

                        return Text(
                          '${floatingProfitLoss.toStringAsFixed(2)}元 (${floatingProfitLossPercent.toStringAsFixed(2)}%)',
                          style: TextStyle(
                            color:
                            floatingProfitLoss >= 0
                                ? Colors.red
                                : Colors.green,
                            fontWeight: FontWeight.bold,
                          ),
                        );
                      },
                    ),
                  ],
                ),
                if (widget.observablePosition.position.realizedProfitLoss !=
                    0) ...[
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      const Text('实际盈亏: '),
                      Text(
                        '${widget.observablePosition.position.realizedProfitLoss.toStringAsFixed(2)}元',
                        style: TextStyle(
                          color:
                          widget
                              .observablePosition
                              .position
                              .realizedProfitLoss >=
                              0
                              ? Colors.red
                              : Colors.green,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),
            // 将价格和涨跌幅放在右上角
            trailing: GetBuilder<PositionController>(
              builder: (controller) {
                final currentPrice =
                    widget.observablePosition.currentPrice.value;
                final changePercent =
                    widget.observablePosition.changePercent.value;
                final bool isRising = changePercent >= 0;
                final Color priceColor = isRising ? Colors.red : Colors.green;

                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      currentPrice.toStringAsFixed(2),
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: priceColor,
                      ),
                    ),
                    Text(
                      changePercent >= 0
                          ? '+${changePercent.toStringAsFixed(2)}%'
                          : '${changePercent.toStringAsFixed(2)}%',
                      style: TextStyle(color: priceColor),
                    ),
                  ],
                );
              },
            ),
            onTap: null,
          ),

          // 操作按钮行
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 展开/收起按钮
                GetBuilder<PositionController>(
                  builder: (controller) {
                    return IconButton(
                      icon: Icon(
                        widget.observablePosition.isExpanded.value
                            ? Icons.expand_less
                            : Icons.expand_more,
                      ),
                      onPressed: () {
                        widget.observablePosition.isExpanded.value =
                        !widget.observablePosition.isExpanded.value;
                        controller.update(); // 手动触发更新
                      },
                    );
                  },
                ),

                // 操作按钮 - 使用Expanded确保不会溢出
                Expanded(
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        ElevatedButton.icon(
                          icon: const Icon(Icons.add, size: 18),
                          label: const Text('买入'),
                          onPressed: _addBuyRecord,
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton.icon(
                          icon: const Icon(Icons.monetization_on, size: 18),
                          label: const Text('卖出'),
                          onPressed: _sellStock,
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton.icon(
                          icon: const Icon(Icons.history, size: 18),
                          label: const Text('历史'),
                          onPressed: _showTradeHistory,
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 展开的交易记录
          GetBuilder<PositionController>(
            builder: (controller) {
              final isExpanded = widget.observablePosition.isExpanded.value;
              if (!isExpanded) {
                return const SizedBox.shrink();
              }

              return Column(
                children: [
                  const Divider(),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    child: Column(
                      children: [
                        // 买入记录
                        ...widget.observablePosition.position.buyRecords.map(
                              (record) => _buildBuyRecordRow(record),
                        ),

                        // 卖出记录
                        ...widget.observablePosition.position.sellRecords.map(
                              (record) => _buildSellRecordRow(record),
                        ),
                      ],
                    ),
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildBuyRecordRow(BuyRecordModel record) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          const Icon(Icons.arrow_downward, color: Colors.red, size: 16),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '买入: ${record.buyPrice.toStringAsFixed(2)} × ${record.quantity}股',
                ),
                Text('剩余: ${record.remainingQuantity}股'),
              ],
            ),
          ),
          Row(
            children: [
              IconButton(
                icon: const Icon(Icons.edit, size: 16),
                onPressed: () {
                  Get.toNamed('/editBuyRecord', arguments: record.id);
                },
                tooltip: '编辑',
              ),
              IconButton(
                icon: const Icon(Icons.delete, size: 16),
                onPressed: () {
                  _showDeleteBuyRecordDialog(record.id);
                },
                tooltip: '删除',
                color: Colors.red,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSellRecordRow(SellRecordModel record) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          const Icon(Icons.arrow_upward, color: Colors.green, size: 16),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '卖出: ${record.sellPrice.toStringAsFixed(2)} × ${record.sellQuantity}股',
                ),
                Text(_formatDate(record.sellDate)),
              ],
            ),
          ),
          IconButton(
            icon: const Icon(Icons.delete, size: 16),
            onPressed: () {
              _showDeleteSellRecordDialog(record.id, record.buyRecordId);
            },
            tooltip: '删除',
            color: Colors.red,
          ),
        ],
      ),
    );
  }

  void _showDeleteBuyRecordDialog(int id) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("确认删除"),
          content: const Text("确定要删除这条买入记录吗？相关的卖出记录也将被删除。"),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _controller.deleteBuyRecord(id);
              },
              child: const Text("删除", style: TextStyle(color: Colors.red)),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteSellRecordDialog(int id, int buyRecordId) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("确认删除"),
          content: const Text("确定要删除这条卖出记录吗？对应的买入记录剩余数量将恢复。"),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _controller.deleteSellRecord(id, buyRecordId);
              },
              child: const Text("删除", style: TextStyle(color: Colors.red)),
            ),
          ],
        );
      },
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}